package com.xiaohong.goods.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaohong.goods.pojo.Goods;
import com.xiaohong.goods.pojo.Sku;
import com.xiaohong.goods.pojo.SpecParam;
import com.xiaohong.goods.pojo.Spu;
import com.xiaohong.goods.service.*;
import entity.Result;
import entity.StatusCode;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Tag(name = "Spu接口文档")
@RestController
@RequestMapping("/spu")
@CrossOrigin
public class SpuController {

    @Autowired
    private SpuService spuService;

    @Autowired
    private SpecParamService specParamService;

    @Autowired
    private SkuService skuService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryService categoryService;

    /***
     * 分页条件搜索实现Spu
     * @param spu
     * @param page
     * @param size
     * @return
     */
    @Operation(summary = "条件分页查询Spu",description = "所需权限：")
    @Parameters({
            @Parameter(in = ParameterIn.PATH, name = "page", description = "当前页", required = true),
            @Parameter(in = ParameterIn.PATH, name = "size", description = "每页显示条数", required = true)
    })
    @PostMapping(value = "/search/{page}/{size}" )
    public Result<Page> findPage(@RequestBody(required = false) @Parameter(name = "Spu对象",required = true) Spu spu, @PathVariable int page, @PathVariable  int size){
        //调用SpuService实现分页条件查询Spu
        Page pageInfo = spuService.findPage(spu, page, size);
        return new Result<Page>(true,StatusCode.OK,"查询成功",pageInfo);
    }

    /***
     * 分页搜索实现Spu
     * @param page:当前页
     * @param size:每页显示多少条
     * @return
     */
    @Operation(summary = "分页查询Spu",description = "所需权限：")
    @Parameters({
            @Parameter(in = ParameterIn.PATH, name = "page", description = "当前页", required = true),
            @Parameter(in = ParameterIn.PATH, name = "size", description = "每页显示条数", required = true)
    })
    @GetMapping(value = "/search/{page}/{size}" )
    public Result<Page> findPage(@PathVariable  int page, @PathVariable  int size){
        //调用SpuService实现分页查询Spu
        Page pageInfo = spuService.findPage(page, size);
        return new Result<Page>(true,StatusCode.OK,"查询成功",pageInfo);
    }

    /***
     * 多条件搜索Spu数据
     * @param spu
     * @return
     */
    @Operation(summary = "多条件查询Spu",description = "所需权限：")
    @PostMapping(value = "/search" )
    public Result<List<Spu>> findList(@RequestBody(required = false) @Parameter(name = "Spu对象",required = true) Spu spu){
        //调用SpuService实现条件查询Spu
        List<Spu> list = spuService.findList(spu);
        return new Result<List<Spu>>(true,StatusCode.OK,"查询成功",list);
    }

    /***
     * 根据Id删除spu数据
     * @param id
     * @return
     */
    @Operation(summary = "根据ID删除Spu",description = "所需权限：")
    @Parameter(in = ParameterIn.PATH, name = "id", description = "ID", required = true)
    @DeleteMapping(value = "/{id}" )
    public Result delete(@PathVariable String id){
        //调用SpuService实现根据ID删除
        spuService.delete(id);
        return new Result(true,StatusCode.OK,"删除成功");
    }

    /***
     * 根据ID修改Spu数据
     * @param spu
     * @param id
     * @return
     */
    @Operation(summary = "根据ID修改Spu",description = "所需权限：")
    @Parameter(in = ParameterIn.PATH, name = "id", description = "ID", required = true)
    @PutMapping(value = "/{id}" )
    public Result update(@RequestBody @Parameter(name = "Spu对象",required = true) Spu spu, @PathVariable String id){
        // 补充id
        spu.setId(id);
        //调用SpuService实现修改Spu
        spuService.update(spu);
        return new Result(true,StatusCode.OK,"修改成功");
    }

    /***
     * 新增商品
     * @param goods
     * @return
     */
    @Operation(summary = "新增商品",description = "所需权限：")
    @PostMapping
    public Result add(@RequestBody  @Parameter(name = "goods对象",required = true) Goods goods){

        Spu spu = goods.getSpu();
        List<Sku> skuList = goods.getSkuList();

        // 获取规格参数集合
        List spuSpecList = spu.getSpecList();
        // spu规格map
        Map<String, Object> spuMap = new HashMap<>();
        Map<String, Object> spuAggregationMap = new HashMap<>();
        Map<String, Object> spuSkuMap = new HashMap<>();
        // 遍历数组
        for (int i = 0; i < spuSpecList.size(); i++) {
            if (spuSpecList.get(i) != null
                    && StringUtils.strip(spuSpecList.get(i).toString(),"[]") != null
                    && StringUtils.strip(spuSpecList.get(i).toString(),"[]").length() != 0
            ) {
                SpecParam byId = specParamService.findById(i);
                //判断是否是搜索聚合规格
                if (byId.getIsAggregation() == 1){
                    spuAggregationMap.put(byId.getName(), spuSpecList.get(i));
                }
                // 判断是否是sku选择聚合参数
                if (byId.getIsSku() == 1) {
                    spuSkuMap.put(byId.getName(), spuSpecList.get(i));
                }
                // 查询对应下标的规格名,加入Map
                spuMap.put(byId.getName(), spuSpecList.get(i));
            }
        }
        // 添加转换好的规格参数到spu
        spu.setSpecItems(JSON.toJSONString(spuMap));
        // 添加搜索聚合规格参数
        spu.setSpecAggregationItems(JSON.toJSONString(spuAggregationMap));
        // 添加sku选择聚合规格参数
        spu.setSpecSkuItems(JSON.toJSONString(spuSkuMap));
        // 添加品牌名
        Integer brandId = spu.getBrandId();
        spu.setBrandChineseName(brandService.findById(brandId).getChineseName());
        spu.setBrandEnglishName(brandService.findById(brandId).getEnglishName());
        // 添加category三级分类名称
        spu.setCategory1Name(categoryService.findById(spu.getCategory1Id()).getName());
        spu.setCategory2Name(categoryService.findById(spu.getCategory2Id()).getName());
        spu.setCategory3Name(categoryService.findById(spu.getCategory3Id()).getName());
        // 添加spu
        spuService.add(spu);

        Integer categoryId = spu.getCategory3Id();
        String categoryName = categoryService.findById(categoryId).getName();


        // 遍历sku集合
        for (int i = 0; i < skuList.size(); i++) {
            Sku sku = skuList.get(i);
            sku.setSpuId(spu.getId());
            sku.setBrandId(brandId);
            sku.setBrandChineseName(spu.getBrandChineseName());
            sku.setBrandEnglishName(spu.getBrandEnglishName());
            sku.setCategoryId(categoryId);
            sku.setCategoryName(categoryName);
            // sku规格map
            Map<String, Object> skuMap = new HashMap<>();
            // 遍历规格
            List skuSpecList = sku.getSpecList();
            for (int y = 0; y < skuSpecList.size(); y++) {
                if (skuSpecList.get(y) != null
                        && StringUtils.strip(skuSpecList.get(y).toString(),"[]") != null
                        && StringUtils.strip(skuSpecList.get(y).toString(),"[]").length() != 0
                ) {
                    // 查询对应下标的规格名,加入Map
                    skuMap.put(specParamService.findById(y).getName(), skuSpecList.get(y));
                }
            }
            // 添加转换好的规格参数到sku
            sku.setSpec(JSON.toJSONString(skuMap));
            // 把imageList转为字符串存入images
            String s = sku.getImageList().toString();
            // 去除[]存入images
            sku.setImages(StringUtils.strip(s,"[]"));

            // 给sku设置名称
            String name = sku.getBrandChineseName()+"("+sku.getBrandEnglishName()+")"+"  ";
            for (Map.Entry<String, Object> entry : skuMap.entrySet()) {
                name += "  "+entry.getValue();
            }
            sku.setName(name);

            // 添加sku
            skuService.add(sku);
        }

        return new Result(true,StatusCode.OK,"添加成功");
    }

    /***
     * 根据ID查询Spu数据
     * @param id
     * @return
     */
    @Operation(summary = "Spu根据ID查询",description = "所需权限：")
    @Parameter(in = ParameterIn.PATH, name = "id", description = "ID", required = true)
    @GetMapping("/{id}")
    public Result<Spu> findById(@PathVariable String id){
        //调用SpuService实现根据ID查询Spu
        Spu spu = spuService.findById(id);
        return new Result<Spu>(true,StatusCode.OK,"查询成功",spu);
    }

    /***
     * 根据ID查询Spu数据及其sku
     * @param id
     * @return
     */
    @Operation(summary = "根据ID查询Spu数据及其sku",description = "所需权限：")
    @Parameter(in = ParameterIn.PATH, name = "id", description = "ID", required = true)
    @GetMapping("/sku/{id}")
    public Result<Spu> findAndSkuById(@PathVariable String id){
        //调用SpuService实现根据ID查询Spu
        Spu spu = spuService.findById(id);
        spu.setSkuList(skuService.findAllBySpuId(spu.getId()));
        return new Result<Spu>(true,StatusCode.OK,"查询成功",spu);
    }

    /***
     * 查询Spu全部数据及其所有sku集合
     * @return
     */
    @Operation(summary = "查询Spu全部数据及其所有sku集合",description = "所需权限：")
    @GetMapping
    public Result<List<Spu>> findAll(){
        //调用SpuService实现查询所有Spu
        List<Spu> list = spuService.findAll();
        for (Spu spu : list) {
            spu.setSkuList(skuService.findAllBySpuId(spu.getId()));
        }
        return new Result<List<Spu>>(true, StatusCode.OK,"查询成功",list) ;
    }

    /***
     * 查询所有已审核并上架Spu及其状态正常sku集合
     * @return
     */
    @Operation(summary = "查询所有已审核并上架Spu及其状态正常sku集合",description = "所需权限：")
    @GetMapping("/market")
    public Result<List<Spu>> findAllMarket(){
        //调用SpuService实现查询所有Spu
        List<Spu> list = spuService.findAllMarket();
        for (Spu spu : list) {
            spu.setSkuList(skuService.findAllMarketBySpuId(spu.getId()));
        }
        return new Result<List<Spu>>(true, StatusCode.OK,"查询成功",list) ;
    }

}
